/*
 * HashTable.cpp
 *
 *  Created on: 11/10/2011
 *      Author: gisedaye
 */

#include "HashTable.h"

HashTable::HashTable(string hashTableFilename) {
	this->hashTableFile=hashTableFilename;
	if(!FileLoader::fileExists(this->hashTableFile)){
			FileLoader::createFile(this->hashTableFile);

	}
	this->size=FileLoader::getHashTableSize(this->hashTableFile);
}

string HashTable::searchRecord(Record * record){

	int dispersionNumber=record->getDispersionNumber(this->size);
	cout<<"DispersionNumb: "<<dispersionNumber<<endl;
	string bucketNumber=FileLoader::getBucketNumberFromFile(this->hashTableFile,dispersionNumber);

	return bucketNumber;
}

int HashTable::getValue(int position){

	string bucketNumber=FileLoader::getBucketNumberFromFile(this->hashTableFile,position);
	return Utils::stringToInt(bucketNumber);
}

void HashTable::insertValue(int position, int value){
	cout<<"HASHTABLE"<<endl;
	cout<<"POS: "<<position<<endl;
	cout<<"VALUE: "<<value<<endl;

	FileWritable::writeToFilePosition(this->hashTableFile,position,Utils::intToString(value));
	this->size++;
}

void HashTable::duplicateSize(){
	int tableSize=this->size;
	int i=0;
	string data="";
	while(i<=tableSize){
		data=FileLoader::readFromFile(this->hashTableFile,i,sizeof(unsigned int));
		FileWritable::writeToFileEnd(this->hashTableFile,data);
		i++;
	}
	this->size = this->size*2;
}

void HashTable::modifyBucketNumber(int dispersion, int value){
	int start=dispersion*BUCKET_SIZE;
	FileWritable::writeToFilePosition(this->hashTableFile,start,Utils::intToString(value));
}
void HashTable::modifyBucketNumberJumps(int start, int dispersion, int bucketNumber){
	int i = start;
	do{
		if ((i+dispersion)>=this->size)
			i=i+dispersion-this->size;
		else
			i+=dispersion;
		this->modifyBucketNumber(i, bucketNumber);

	}while(i!=start);
}
int HashTable::getSize(){
	return this->size;
}
void HashTable::setSize(int size){
	this->size=size;
}
int HashTable::getMaxBucketNumber(){
	return this->maxBucketNumber;
}
void HashTable::setMaxBucketNumber(int maxBucketNumber){
	this->maxBucketNumber=maxBucketNumber;
}

bool HashTable::isMirrored(){
	int halfPos=this->getSize()%2;
	for (unsigned int i=0; i<halfPos; i++){
		if(this->getValue(i)!=this->getValue(halfPos+i)){
			return false;
		}
	}
	return true;
}

void HashTable::truncate(){
	for (unsigned int i=(this->size/2+1); i<this->size;i++){
		FileWritable::writeToFilePosition(this->hashTableFile,i,"");
	}
	this->size=this->size/2;
}
HashTable::~HashTable() {

}
